﻿<template>
  <!--Container为背景-->
  <Container>
    <!--标题内容-->
    <main class="content">
      <div class="header">
        <h2>我的提问箱</h2>
        <el-button
          type="primary"
          @click="isCreatedialogVisible = true"
        >创建提问箱</el-button>
      </div>

      <!--创建提问箱弹窗-->
      <CreateBoxPage
        v-if="isCreatedialogVisible"
        @close="isCreatedialogVisible = false"
        @submit="handleCreateBoxSubmit"
      />
      <!--编辑提问箱弹窗-->
      <EditBoxPage
        :visible="isEditDialogVisible"
        :boxData="{ name: selectedBoxData.name, description: selectedBoxData.text ,id:selectedBoxData.id }"
        @close="isEditDialogVisible = false"
        @update="handleUpdateBox"
        @delete="handleDeleteBox"
      />
      <!-- 内容卡片 -->
      <Card :items="displayedItems">
        <template #copylink="{ item }">
          <Copylink :url="item.url" />
        </template>
        <template #edit="{ item }">
          <el-button
            size="small"
            type="text"
            @click="editQuestionBox(item)"
          >
            <el-icon style="font-size: 20px;">
              <Edit />
            </el-icon>
            编辑
          </el-button>
        </template>
      </Card>
      <!--分页-->
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="totalItems"
        class="pagination"
      />
    </main>
    <!--底部菜单-->
    <Footmenu />
    <Wave />
  </Container>
</template>
  
  <script>
import Container from '../components/main/container.vue';
import Footmenu from '../components/main/footmenu.vue';
import Copylink from '../components/main/copylink.vue';
import Card from '../components/main/card.vue';
import CreateBoxPage from '../components/main/createboxPage.vue';
import EditBoxPage from '../components/main/editboxPage.vue';
import { ref, computed, onMounted } from 'vue';
import { get } from "@/net";
import { ElMessage } from 'element-plus';
export default {
  name: 'App',
  components: {
    Container, Footmenu, Copylink, Card, CreateBoxPage, EditBoxPage
  },
  setup () {
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(50);
    const aid = ref(1);
    const allItems = ref([]);

    // 控制弹窗的显示
    const isCreatedialogVisible = ref(false);

    // 创建提问箱
    const handleCreateBoxSubmit = (formData) => {
      //向后端发送创建提问箱相关内容
      //后端返回新建提问箱数据（id）
      const randomId = Math.floor(Math.random() * 100) + 1
      totalItems.value++; // 更新总数
      // 创建新提问箱项
      const newItem = {
        id: randomId,
        name: formData.name,
        text: formData.description,
        url: "https://www.baidu.com",
        oid: null
      }
      // 添加到 allItems 数组
      allItems.value.push(newItem);
    };


    const fetchData = async () => {
      get(
        "/question_box/get_my_create_question_box", { id: aid.value },
        (message) => {
          console.log(message.data);
          allItems.value = message.data.boxes; // 鍋囪杩斿洖鐨勬暟鎹粨鏋勪腑鏈� items 瀛楁
          totalItems.value = message.data.total; // 鍋囪杩斿洖鏁版嵁鍖呭惈 total 瀛楁
        },
        () => {
          store.clearAccount();
        }
      );
    };

    onMounted(() => {
      fetchData(); // 组件加载时请求数据
    });


    const displayedItems = computed(() => {
      const start = 0;
      const end = start + pageSize.value;
      return allItems.value.slice(start, end);
    });
    // 椤电爜鍙樺寲鏃剁殑澶勭悊鍑芥暟
    const handlePageChange = (page) => {
      currentPage.value = page;
      console.log('当前页数:', page);
      fetchData();
    };

    // 控制编辑弹窗的显示状态
    const isEditDialogVisible = ref(false);
    const selectedBoxData = ref({});
    // 定义 editQuestionBox 函数
    const editQuestionBox = (item) => {
      selectedBoxData.value = { ...item }; // 复制选中的提问箱数据
      isEditDialogVisible.value = true;    // 显示编辑弹窗
    };

    //编辑提问箱
    const handleUpdateBox = (updatedData) => {
      //need fill 先发送给服务器请求，服务器响应成功后再渲染
      const index = allItems.value.findIndex((item) => item.id === updatedData.id);
      if (index !== -1) {
        // 强制触发响应式更新
        allItems.value[index] = Object.assign({}, allItems.value[index], {
          name: updatedData.name,
          text: updatedData.description,
        });
        ElMessage.success('提问箱已更新！');
      } else {
        ElMessage.success('提问箱更新失败！');
      }
      isEditDialogVisible.value = false;  // 关闭弹窗
    };

    //删除提问箱
    const handleDeleteBox = (idToDelete) => {
      // 找到要删除的项的索引
      const index = allItems.value.findIndex((item) => item.id === idToDelete);
      totalItems.value--; // 更新总数
      if (index !== -1) {
        // 从数组中删除该项
        allItems.value.splice(index, 1);
        ElMessage.success("提问箱已成功删除！");
      } else {
        ElMessage.error("未找到指定的提问箱！");
      }
      isEditDialogVisible.value = false;
    };
    return {
      currentPage, totalItems, pageSize,
      displayedItems, handlePageChange,
      isCreatedialogVisible,
      handleCreateBoxSubmit,
      editQuestionBox, isEditDialogVisible, selectedBoxData, handleUpdateBox, handleDeleteBox
    };

  },
};
  </script>
  
  
  <style scoped>
.content {
  height: 90%;
  padding: 1%;
  background-color: #ffffff; /* 确保表格区域背景为白色 */
}

.header {
  height: 10%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination {
  height: 10%;
  display: flex;
  justify-content: center;
}
</style>
  